package wenjun.du.androidart.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.widget.Scroller
import androidx.appcompat.R
import androidx.appcompat.widget.AppCompatButton
import kotlin.math.abs

/**
 * 自定义控件 查看touch传递事件规律
 *
 * */
class ExOutButton(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
    AppCompatButton(context, attrs, defStyleAttr) {

    companion object {
        private const val TAG = "ExRelative_ExOutButton"
    }

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, R.attr.buttonStyle)


    private val scroller: Scroller = Scroller(context)


    fun smoothScrollTo(destX: Int, destY: Int) {
        val scrollX = scrollX  //等于控件的左边缘到view内容左边缘的距离， 默认为0
        val scrollY = scrollY //等于控件的上边缘到view内容上边缘的距离， 默认为0
        val detX = destX - scrollX
        val detY = destY - scrollY
        scroller.startScroll(scrollX, scrollY, detX, detY, 1000)
        invalidate()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        Log.d(
            TAG,
            "onMeasure() called with: widthMeasureSpec = $widthMeasureSpec, heightMeasureSpec = $heightMeasureSpec"
        )
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        Log.d(
            TAG,
            "onLayout() called with: changed = $changed, left = $left, top = $top, right = $right, bottom = $bottom"
        )
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        Log.d(TAG, "onDraw() called with: canvas = $canvas")
    }

    //控件绘制的时候  会调用该方法
    override fun computeScroll() {
        super.computeScroll()
        Log.d(TAG, "son computeScroll() called thread name ${Thread.currentThread().name}")
        if (scroller.computeScrollOffset()) {
            // 移动的是内容 并没有改变view的布局位置
            scrollTo(scroller.currX, scroller.currY)
            postInvalidate()
        }
    }

    /**
     * 外部拦截法
     *
     * */
    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        Log.d(TAG, "son onTouchEvent() called with: event = ${ViewUtil.getStringAction(event?.action)}")
        return super.onTouchEvent(event)
    }

}